import {connect} from 'dva';
import {Table, Pagination, Popconfirm} from 'antd';
import {routerRedux} from 'dva/router';
import styles from './Users.css';
import {PAGE_SIZE} from '../constants';
import UserEditComp from "./UserEditComp";

function Users({dispatch, list: dataSource, loading, total, page: current, editFlag, editRecord}) {

  function deleteHandler(id) {
    dispatch({
      type: "users/del",
      payload: id
    });
  }

  function editHandler(record, e) {
    if (e) {
      e.preventDefault();
    }
    dispatch({
      type: "users/edit",
      payload: record
    });
  }

  function editFinishHandler(e) {
    if (e) {
      e.preventDefault();
    }
    dispatch({
      type: "users/editFinish"
    });
  }

  function updateHandler(record) {
    dispatch({
      type: "users/update",
      payload: record
    });
  }

  function pageChangeHandler(page) {
    dispatch(routerRedux.push({
      pathname: '/users',
      query: {page},
    }));
  }

  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: text => <a href="">{text}</a>,
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: 'Website',
      dataIndex: 'website',
      key: 'website',
    },
    {
      title: 'Operation',
      key: 'operation',
      render: (text, record) => (
        <span className={styles.operation}>
          <a href="javscript:void(0);" onClick={editHandler.bind(this, record)}>Edit</a>
          <Popconfirm title="Confirm to delete?" onConfirm={deleteHandler.bind(null, record.id)}>
            <a href="javscript:void(0);">Delete</a>
          </Popconfirm>
        </span>
      ),
    },
  ];

  return (
    <div className={styles.normal}>
      <div>
        <UserEditComp visibled={editFlag} record={editRecord}
                       onOk={updateHandler.bind(this)} onHideHandler={editFinishHandler.bind(this)}/>
      </div>
      <div>
        <Table
          loading={loading}
          columns={columns}
          dataSource={dataSource}
          rowKey={record => record.id}
          pagination={false}
        />
        <Pagination
          className="ant-table-pagination"
          total={total}
          current={current}
          pageSize={PAGE_SIZE}
          onChange={pageChangeHandler}
        />
      </div>
    </div>
  );
}

function mapStateToProps(state) {
  const {list, total, page, editFlag, editRecord} = state.users || {};
  return {
    list,
    total,
    page,
    editFlag,
    editRecord,
    loading: state.loading.models.users
  };
}

export default connect(mapStateToProps)(Users);
